import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Random;


public class Main {

	public static void main(String[] args) {
		
		
		try {
			File f = new File("results.txt");
			if(f.exists())
				f.delete();
			f.createNewFile();

			FileWriter fstream = new FileWriter(f);
		    BufferedWriter out = new BufferedWriter(fstream);
		    
		    //for statistics
		    WriteExcel1.instance.setOutputFile("e:/programs/eclipse/Workspace/prisonerDilem/lars.xls");
		    
		    
			Generation gen = new Generation(Data.generationSize),newGen;
			for(int i=0; i< Data.numberOfGenerations ;i++){
				newGen=Generation.createNewGeneration(gen);
				gen=newGen;
			}
			newGen=Generation.createNewGeneration(gen);
			Collections.sort(gen.chromosomeList,new MinTimeInPrisonComparator());
			Collections.reverse(gen.chromosomeList);
			Chromosome x=gen.chromosomeList.get(0);
			exportToTempCsv(x);
			for(int i=0; i < x.data.length; i++)
				System.out.print(x.data[i]);
			
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	private static void exportToTempCsv(Chromosome winner){
		
		for(int i=0;i<10000;i++){
			Random r= new Random();
			int tempArr[]=new int[Data.chromozomSize];
			for(int j=0;j<Data.chromozomSize;j++){
				tempArr[j]=r.nextInt(2);
			}
			Chromosome temp = new Chromosome(tempArr);
			winner.play(temp);
		}
		
		try
		{
			FileWriter writer = new FileWriter("temp.csv");
			writer.append(String.valueOf(Data.generationSize));
			writer.append(',');
			writer.append(String.valueOf(Data.numberOfGenerations));
			writer.append(',');
			writer.append(String.valueOf(Data.fitnessMethod.toString()));
			writer.append(',');
			writer.append(String.valueOf(Data.fromGenerationGamesToPlayPerChromo));
			writer.append(',');
			writer.append(String.valueOf(Data.newRandomGamesToPlayPerChromo));
			writer.append(',');
			writer.append(String.valueOf(Data.bitMutateProbability));
			writer.append(',');
			writer.append(String.valueOf(Data.positiveElitismSize));
			writer.append(',');
			writer.append(String.valueOf(Data.crossOverMethodSize));
			writer.append(',');
			writer.append(String.valueOf(winner.timeInPrison/winner.gamesPlayed));
			writer.append(',');
			writer.append(String.valueOf(winner.gamesWon));
			writer.append('\n');
			writer.flush();
			writer.close();
		  
		}
		catch(Exception e)
		{
		  e.printStackTrace();
		}
	}

}
